package filepro;

import java.io.*;
import java.nio.charset.Charset;

/**
 * 文件转码器
 * @author small瑞
 */
public class FileTranscoder {

    /**
     * 构造私有
     */
    private FileTranscoder(){}


    public static FileTranscoder getInstance(){
        return new FileTranscoder();
    }

    public void transcoder(File origin , String originCharset , File dest , String destCharset) throws IOException {
        if(!origin.exists() || !origin.isFile()){
            throw new IOException("不是一个文件或文件不存在!");
        }
        if(!dest.exists()){
            dest.createNewFile();
        }
        FileInputStream inputStream = new FileInputStream(origin);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream , originCharset);

        FileOutputStream outputStream = new FileOutputStream(dest);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,destCharset);
        char[] arr = new char[12];
        int read;
        while((read = inputStreamReader.read(arr, 0, 12))!=-1){
            outputStreamWriter.write(arr,0,read);
        }
        outputStreamWriter.flush();
        outputStream.flush();
        outputStreamWriter.close();
        outputStream.close();
        inputStreamReader.close();
        inputStream.close();

    }
    public static void main(String[] args) throws IOException {
        /*
        File origin = new File("G:\\IO/牵丝戏合集.txt");
        File dest = new File("G:\\IO/try.txt");
        FileTranscoder fileTranscoder = FileTranscoder.getInstance();
        fileTranscoder.transcoder(origin,"UTF-8",dest,"GBK");

         */
        File origin = new File("G:\\IO/file.txt");
        File dest = new File("G:\\IO/file-gbk.txt");
        FileTranscoder fileTranscoder = FileTranscoder.getInstance();
        fileTranscoder.transcoder(origin,"UTF-8",dest,"GBK");

    }
}
